package com.snapan.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 日志拦截器示例
 * 用于记录请求日志和性能监控
 */
public class LogInterceptor implements HandlerInterceptor {
    
    private long startTime;
    
    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        startTime = System.currentTimeMillis();
        
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        String remoteAddr = request.getRemoteAddr();
        
        System.out.println("=== 请求开始 ===");
        System.out.println("URI: " + requestURI);
        System.out.println("Method: " + method);
        System.out.println("Remote Address: " + remoteAddr);
        System.out.println("Time: " + new java.util.Date());
        
        return true; // 返回true表示继续执行，返回false表示中断执行
    }
    
    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 可以在这里添加一些通用的模型数据
        if (modelAndView != null) {
            modelAndView.addObject("interceptorMessage", "这是来自拦截器的消息");
        }
    }
    
    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet渲染了对应的视图之后执行
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long endTime = System.currentTimeMillis();
        long executionTime = endTime - startTime;
        
        String requestURI = request.getRequestURI();
        
        System.out.println("=== 请求结束 ===");
        System.out.println("URI: " + requestURI);
        System.out.println("执行时间: " + executionTime + "ms");
        System.out.println("状态码: " + response.getStatus());
        
        if (ex != null) {
            System.out.println("异常: " + ex.getMessage());
        }
        System.out.println("==================");
    }
}












































